//
//  HttpOperator.m
//  AOP
//
//  Created by SKY on 14-3-19.
//  Copyright (c) 2014年 sky. All rights reserved.
//

#import "HttpOperator.h"
#import "HttpTools.h"
#import "BaseData.h"
#import "QCDeviceManager.h"
#import "MsgCenterInstance.h"




@interface HttpOperator ()

@property (retain, nonatomic) NSString* iNSStringFromClass;

@end

@implementation HttpOperator

@synthesize iNSStringFromClass;
- (void)dealloc{
    [self.postManager clearDelegatesAndCancel];
    _postManager = nil;
    self.iOnUserCancelBlock = nil;
    self.iNSStringFromClass = nil;
    [self deleteBlock];
    [super dealloc];
}
-(void) deleteBlock {
    if (_iOnStartBlock != nil) {
        Release(_iOnStartBlock);

    }
    if (_iOnCompleteBlock != nil) {
        Release(_iOnCompleteBlock);
    }
    if (_iOnErrorBlock != nil) {
        Release(_iOnErrorBlock);
    }
    if (_iOnParamBlock != nil) {
        Release(_iOnParamBlock);
    }
    if (self.iNSStringFromClass != nil) {
        self.iNSStringFromClass = nil;
    }
}




- (id)init{
    self = [super init];
    if (self) {
        self.iTaskID = 1000;
    }
    return self;
}
-(void)connetStart:(void (^)(int d))aStart cancel:(void (^)(int d)) aCancel error:(void (^)(int d, THttpOperatorErrorCode e)) aError param:(void (^)(NSString* s))aParam complete: (void (^) (id r, int taskid)) aComplete {
    self.iOnStartBlock = aStart;
    self.iOnUserCancelBlock = aCancel;
    self.iOnErrorBlock = aError;
    self.iOnCompleteBlock = aComplete;
    self.iOnParamBlock = aParam;
}
-(void)connect {
    
    _iTaskID++;
    if (_iTaskID >= 999999) {
        _iTaskID = 0;
    }

    if (self.iOnParamBlock == nil) {
        return;
    }
    self.iOnParamBlock(@"aa");
}

//取消请求
-(void) cancel {

    [self.postManager clearDelegatesAndCancel];
    if (self.iOnUserCancelBlock != nil) {
        self.iOnUserCancelBlock(_iTaskID);
        self.iOnUserCancelBlock  = nil;
    }
    [self deleteBlock];
}


-(id) getAopInstance:(Class) class returnValue:(Class) returnClass {
    self.iNSStringFromClass = NSStringFromClass(returnClass);
    id res = [[AopProxy alloc] initWithNewInstanceOfClass:class delegate:self];
    return res;
}
#pragma mark------AopProxyDelegate
-(void) invokeClass:(NSString*) className method:(NSString*) methodName args:(NSArray*) args{
    NSData* jsonData = [HttpTools getProxyJson:className method:methodName args:args];
    NSString* paramsString = [NSString stringWithFormat:@"json=%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]];
//    post date 打印
    NSData* postData = [paramsString dataUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"post data:%@", paramsString);

    NSString* urlStr = TMPT_SERVER_URL;//@"http://www.baidu.com";
    NSLog(@"request's url is ===%@", urlStr);
    //创建请求
    NSMutableURLRequest *request =
    [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]] autorelease];
    //指定请求方式
    [request setHTTPMethod:@"POST"];
    //指定请求Header
    [HWConfigTool setHttpSystemHeaderWithAFNManager:request];
    //指定请求体
    [request setHTTPBody:postData];
    
    self.postManager = [[[AFHTTPRequestOperationManager alloc] init] autorelease];

    __block typeof(self)this = self;
    //开始请求
    NSOperation *operation = [self.postManager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation1, id responseObject) {
        
        //请求成功
        NSLog(@"operationSuccess---%@,===%@",operation1,responseObject);
        if (![operation1 isCancelled]){
            [this afnetWorkingFinishedWithOperation:operation1 responseObject:responseObject];
        }
    } failure:^(AFHTTPRequestOperation *operation1, NSError *error) {
        NSLog(@"operationFailed---%@",operation1);
        
        if (![operation1 isCancelled]){//请求未被取消
            //请求失败
            [this afnetWorkingFailedWithError:error operation:operation1];
        }
    }];
    
    [self.postManager.operationQueue addOperation:operation];
    
    if (self.iOnStartBlock != nil) {//开始请求
        self.iOnStartBlock(_iTaskID);
    }
}

-(void)afnetWorkingFinishedWithOperation:(AFHTTPRequestOperation *)operation responseObject:(NSDictionary *)response{
 
    __block typeof(self)this = self;

    if ((![response isKindOfClass:[NSDictionary class]])  && (![response isKindOfClass:[NSArray class]])) {
        [ProgressHUD showErrorWithStatus:@"返回数据格式错误"];
        return;
        
    }
    NSError * err;
    NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:response options:0 error:&err];
    NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",jsonString);
    //200是请求成功的请求码
    if (operation.response.statusCode != 200) {
        if (this.iOnErrorBlock) {
            this.iOnErrorBlock(this.iTaskID, EHttp_Operator_StatusCodeError);
            
        }
        return;
    }
    //request.responseString 数据打印
    NSLog(@"request.responseString = %@", operation.response);
    
    if (this.iOnCompleteBlock != nil) {
        
        if (this.iNSStringFromClass != nil) {
            Class class = NSClassFromString(this.iNSStringFromClass);
            BaseData* obj = [[[class alloc] init] autorelease];
            
            [obj decode:jsonString];
            
            if ([self isPreprocessingFinishedWithObject:obj]) {
                this.iOnCompleteBlock(obj, _iTaskID);

            };
            
        }else {
            this.iOnCompleteBlock(nil, _iTaskID);
        }
        
        
    }
    
    
}

-(void)afnetWorkingFailedWithError:(NSError *)error operation:(AFHTTPRequestOperation *)operation
{
    //-999 取消请求的时候会提示
    if (error.code != -999 && operation.response.statusCode != 200) {
        NSLog(@"operation.response.statusCode===%ld",(long)operation.response.statusCode);
        
        NSLog(@"operation.response.statusString===%ld",(long)operation.responseString);

        if (operation.response.statusCode == 500) {
            [ProgressHUD showErrorWithStatus:@"服务器异常!"];
        }else{
            if (![operation isCancelled]){
                [ProgressHUD showErrorWithStatus:@"网络连接错误!"];

            }
        }
    }
}


/**
 成功block回调之前的处理
 */

-(BOOL)isPreprocessingFinishedWithObject:(BaseData *)baseData
{
    BOOL isSuccess = YES;
    if (baseData) {
        
        if (baseData.hasNewMsg > 0) {
            [MsgCenterInstance invokePollingRequest];
        }
//     编号为 -9999跳转登录
        /*
        if (baseData.errCode == [HandicapWinToLoginKey integerValue]) {
            HWUserModel *um = [[HWUserManager sharedInstance] getLoginUser];
            [[HWUserManager sharedInstance] setLoginUser:um];
            [ProgressHUD showSuccessWithStatus:@"登录失效"];


            isSuccess = NO;
        }
         */
    }
    return isSuccess;
}



@end
